from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission


class TeacherPermission(BasePermission):
    """
    只能老师才能访问
    """

    def has_permission(self, request, view):
        user = request.user
        # 拿老师组
        group = Group.objects.get(name='老师')
        # 获取用户组
        groups = user.groups.all()
        return bool(user.is_superuser or group in groups)


class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user  # 获取用户对象
        # 当前登录用户id：request.user.id，想要操作的用户id：int(view.kwargs['pk'])
        return user.id == int(view.kwargs['pk'])


class MyBasePermission(BasePermission):
    def has_permission(self, request, view):
        if request.method in ['GET', 'HEAD', 'OPTION']:
            return True
        if request.user.is_superuser:
            return True
        # if view.action == 'create' or view.action == 'update':
        if view.action in ['create', 'update']:
            user = request.user
            group = Group.objects.get(name='老师')  # 拿老师组
            groups = user.groups.all()  # 获取用户组
            return user.is_superuser or group in groups
        if view.action == 'destroy':
            return request.user.is_superuser


# 把操作用户自动更改为登录用户
def auto_user(func):
    def f(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data['user'] = str(request.user.id)
        return func(self, request, *args, **kwargs)

    return f
